package com.ali.ttt.netty.server.handler;

import com.ali.ttt.netty.common.domain.*;
import com.ali.ttt.netty.common.utils.MessageUtil;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @Author : yuxl
 * @create 2024/7/2 11:11 PM
 */
@Slf4j
@Service
@ChannelHandler.Sharable
public class LoginRequestHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("收到一个新的连接，但是没有登录 {}", ctx.channel().id());
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String messageStr = ((ByteBuf)msg).toString(StandardCharsets.UTF_8);
        Message<Client> message = JSONObject.parseObject(messageStr,Message.class);
        if(!"/login".equals(message.getPath())){
            super.channelRead(ctx, msg);
            return;
        }
        Client client = JSONObject.parseObject(JSONObject.toJSONString(message.getMsg()),Client.class);
        ServerSession session = new ServerSession(ctx.channel());
        boolean isValidUser = SessionMap.inst().hasLogin(client);
        Message<LoginRes> resMessage = new Message<>("/login");
        LoginRes res = new LoginRes();
        if (isValidUser) {
            res.setMsg("无需重复登录");
        }else{
            res.setSuccess(true);
            session.setClient(client);
            session.reverseBind();
            res.setSId(session.getSessionId());
            res.setMsg("登录成功");
        }
        resMessage.setMsg(res);
        MessageUtil.send(ctx,resMessage);
    }
}
